package com.enation.app.javashop.buyer.api.promotion;

import com.enation.app.javashop.core.promotion.PromotionErrorCode;
import com.enation.app.javashop.core.promotion.seckill.model.dto.SeckillQueryParam;
import com.enation.app.javashop.core.promotion.seckill.model.enums.SeckillGoodsApplyStatusEnum;
import com.enation.app.javashop.core.promotion.seckill.model.enums.SeckillStatusEnum;
import com.enation.app.javashop.core.promotion.seckill.model.vo.SeckillApplyVO;
import com.enation.app.javashop.core.promotion.seckill.model.vo.SeckillVO;
import com.enation.app.javashop.core.promotion.seckill.model.vo.TimeLineGoods;
import com.enation.app.javashop.core.promotion.seckill.model.vo.TimeLineVO;
import com.enation.app.javashop.core.promotion.seckill.service.SeckillGoodsManager;
import com.enation.app.javashop.core.promotion.seckill.service.SeckillManager;
import com.enation.app.javashop.core.promotion.seckill.service.SeckillRangeManager;
import com.enation.app.javashop.core.trade.cart.service.CartOriginDataManager;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 限时抢购相关API
 *
 * @author Snow create in 2018/7/23
 * @version v2.0
 * @since v7.0.0
 */
@RestController
@RequestMapping("/promotions/seckill")
@Api(description = "限时抢购相关API")
@Validated
public class SeckillBuyerController {

    @Autowired
    private SeckillManager seckillManager;

    @Autowired
    private SeckillGoodsManager seckillApplyManager;

    @Autowired
    private SeckillRangeManager seckillRangeManager;

    @Autowired
    private CartOriginDataManager cartOriginDataManager;

    @ApiOperation(value = "读取秒杀时刻-A")
    @ResponseBody
    @GetMapping(value = "/time-line")
    public List<TimeLineVO> readTimeLine(@RequestParam String city) {
        List<TimeLineVO> timeLineVOList = this.seckillRangeManager.readTimeList(city);
        return timeLineVOList;
    }


    @ApiOperation(value = "根据参数读取限时抢购的商品列表-A")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "range_time", value = "时刻", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_no", value = "页码", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_size", value = "条数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "city", value = "城市", dataType = "String", paramType = "query")
    })
    @GetMapping("/goods-list")
    public Page goodsList(@ApiIgnore Integer rangeTime,@ApiIgnore String city, @ApiIgnore Integer pageSize, @ApiIgnore Integer pageNo) {
        pageNo=1;
        pageSize=1000;

        if (rangeTime == null) {
            throw new ServiceException(PromotionErrorCode.E400.code(), "时刻不能为空");
        }

        if (rangeTime > 24) {
            throw new ServiceException(PromotionErrorCode.E400.code(), "时刻必须是0~24的整数");
        }

        SeckillQueryParam param = new SeckillQueryParam();
        param.setPageNo(pageNo);
        param.setPageSize(pageSize);

        List list = this.seckillApplyManager.getSeckillGoodsByRangeTime(rangeTime,city);
        long dataTotal = 0;
        if (list != null && !list.isEmpty()) {
            dataTotal = list.size();
        }

        Page page = new Page();
        page.setData(list);
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        page.setDataTotal(dataTotal);
        return page;

    }

    /**
     * jfeng 新增接口
     */
    @ApiOperation(value = "查询限时抢购商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "seckill_id", value = "限时抢购活动id", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_no", value = "页数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_size", value = "条数", dataType = "int", paramType = "query"),
    })
    @GetMapping("/seckill-list")
    public Page<SeckillApplyVO> list(@ApiIgnore Integer seckillId,
                                     @ApiIgnore Integer pageNo, @ApiIgnore Integer pageSize) {

        SeckillQueryParam queryParam = new SeckillQueryParam();
        queryParam.setPageNo(pageNo);
        queryParam.setPageSize(pageSize);
        queryParam.setSeckillId(seckillId);
        queryParam.setStatus(SeckillGoodsApplyStatusEnum.PASS.value());
        queryParam.setStartDay(DateUtil.startOfTodDay());
        Page webPage = this.seckillApplyManager.list(queryParam);
        return webPage;
    }


    @GetMapping(value = "/{city}/seckill")
    @ApiOperation(value = "查询当前城市活动详情（所有商品）-B ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "city", value = "所在城市", required = true, dataType = "String", paramType = "path")
    })
    public SeckillVO getSeckill(@ApiIgnore @PathVariable("city") String city) {
        SeckillVO seckill = this.seckillManager.getSeckillDetailByCity(city);
        return seckill;
    }


    @GetMapping(value = "/currentSeckill")
    @ApiOperation(value = "查询当前城市活动详情（当前时间点商品）-B ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "city", value = "所在城市", required = true, dataType = "String", paramType = "query")
    })
    public SeckillVO currentSeckill(@RequestParam(value = "city",required = false) String city ) {
        SeckillVO seckill = this.seckillManager.getSeckillDetailByCity(city);
        // 解析当前时间range_time的秒杀商品
        if (seckill == null || CollectionUtils.isEmpty(seckill.getTimeLineGoodsList())) {
            return seckill;
        }
        Integer currentHour= LocalTime.now().getHour();
        List<TimeLineGoods> timeLineGoodsList = seckill.getTimeLineGoodsList();
        Integer index=0;
        for (int i = 0; i < timeLineGoodsList.size(); i++) {
            TimeLineGoods timeLineGoods = timeLineGoodsList.get(i);
            Integer rangeTime = timeLineGoods.getTimeLine();
            if(currentHour>=rangeTime && timeLineGoods.getDistanceStartTime()==null){
                index=i;
            }
        }
        TimeLineGoods currentGoods=timeLineGoodsList.get(index);
        seckill.setTimeLineGoodsList(Arrays.asList(currentGoods));
        return seckill;
    }

}
